package log

import (
	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/bson"
	"higame/modules/log"
	"higame/modules/utils"
	"net/http"
)

// 用户登录日志-管理员权限
func loginLog(ctx *gin.Context) {
	pageNum := utils.StringToInt64(ctx.PostForm("page_num"), 1)
	username, err := fetchUsernameForAuth(ctx)
	if err != nil {
		log.Error.Println(err)
		ctx.JSON(500, gin.H{
			"code": 500,
			"msg":  "服务器内部出错",
			"data": nil,
		})
		return
	}

	list := FindManyLoginLog(pageNum, bson.M{
		"username": username,
	})
	count, _ := CountLoginLog(bson.M{
		"username": username,
	})
	str := ""
	if count == 0 {
		str = "没有查询到数据！"
	} else {
		str = utils.JoinString("共%v页%v行 当前在第%v页", count/20+1, count, pageNum+1)
	}
	len := len(list)
	if len > 10 {
		len = 10
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  str,
		"data": gin.H{
			"list":  list[:len],
			"total": count,
		},
	})
}

func integralLog(ctx *gin.Context) {
	pageNum := utils.StringToInt64(ctx.PostForm("page_num"), 1)
	username, err := fetchUsernameForAuth(ctx)
	if err != nil {
		log.Error.Println(err)
		ctx.JSON(500, gin.H{
			"code": 500,
			"msg":  "服务器内部出错",
			"data": nil,
		})
		return
	}

	list := FindManyIntegralLog(pageNum, bson.M{
		"username": username,
	})
	count, _ := CountIntegralLog(bson.M{
		"username": username,
	})
	str := ""
	if count == 0 {
		str = "没有查询到数据！"
	} else {
		str = utils.JoinString("共%v页%v行 当前在第%v页", count/20+1, count, pageNum+1)
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  str,
		"data": gin.H{
			"list":  list,
			"total": count,
		},
	})

}

func allLoginLog(ctx *gin.Context) {
	pageNum := utils.StringToInt64(ctx.PostForm("page_num"), 1)
	filter := ctx.PostForm("filter")
	text := ctx.PostForm("text")

	where := bson.M{}
	if filter != "" {
		where[filter] = bson.M{
			"$regex":   text,
			"$options": "$i",
		}
	}

	list := FindManyLoginLog(pageNum, where)
	count, _ := CountLoginLog(where)
	str := ""
	if count == 0 {
		str = "没有查询到数据！"
	} else {
		str = utils.JoinString("共%v页%v行 当前在第%v页", count/20+1, count, pageNum)
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  str,
		"data": gin.H{
			"list":  list,
			"total": count,
		},
	})
}

func allIntegralLog(ctx *gin.Context) {
	pageNum := utils.StringToInt64(ctx.PostForm("page_num"), 1)
	filter := ctx.PostForm("filter")
	text := ctx.PostForm("text")

	where := bson.M{}
	if filter != "" {
		where[filter] = bson.M{
			"$regex":   text,
			"$options": "$i",
		}
	}
	list := FindManyIntegralLog(pageNum, where)
	count, _ := CountIntegralLog(where)
	str := ""
	if count == 0 {
		str = "没有查询到数据！"
	} else {
		str = utils.JoinString("共%v页%v行 当前在第%v页", count/20+1, count, pageNum)
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  str,
		"data": gin.H{
			"list":  list,
			"total": count,
		},
	})

}
